//
//  YYQRCodeView.m
//  XinMi
//
//  Created by 蓓蕾 on 2021/8/11.
//  Copyright © 2021 Yang. All rights reserved.
//

#import "YYQRCodeView.h"
#import <AVFoundation/AVFoundation.h>

/** 扫描框的宽度与高度 */
static const NSInteger staticHeight = 250;
/** 扫描框距离顶部的距离，设置为0 是，扫描框居中 */
static const NSInteger staticTopMargin = 80;

//颜色(默认支付宝蓝)
#define STYLECOLOR [UIColor colorWithRed:57/255.f green:187/255.f blue:255/255.f alpha:1.0]

@interface YYQRCodeView ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic , strong ) AVCaptureDevice         *   device;
@property (nonatomic , strong ) AVCaptureDeviceInput    *   input;
@property (nonatomic , strong ) AVCaptureMetadataOutput *   output;
@property (nonatomic , strong ) AVCaptureSession        *   session;
@property (nonatomic , strong ) AVCaptureVideoPreviewLayer *previewlayer;
@property (nonatomic , strong ) UIView                  *   hudView;

@end

@implementation YYQRCodeView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        //扫描范围限制
        CGRect outPutRect = [self rectOfInterestByScanViewRect:CGRectMake(CGRectGetWidth(self.bounds) / 2 - staticHeight / 2,staticTopMargin,staticHeight,staticHeight)];
        if (staticTopMargin == 0) {
            outPutRect = CGRectMake(CGRectGetWidth(self.bounds) / 2 - staticHeight / 2, CGRectGetHeight(self.bounds) / 2 - staticHeight / 2, staticHeight, staticHeight);
            
            outPutRect = [self rectOfInterestByScanViewRect:outPutRect];
        }
        self.backgroundColor = UIColor.grayColor;
        AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        BOOL isAvailableA = authorizationStatus == AVAuthorizationStatusRestricted || authorizationStatus == AVAuthorizationStatusDenied;
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] && isAvailableA == NO){//判断相机
            _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
            _input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];
            _output = [[AVCaptureMetadataOutput alloc] init];
            [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
            [_output setRectOfInterest:outPutRect];//扫描范围限制
            _session = [[AVCaptureSession alloc] init];
            [_session setSessionPreset:AVCaptureSessionPresetHigh];
            if ([_session canAddInput:_input]) {
                [_session addInput:_input];
            }
            if ([_session canAddOutput:_output]) {
                [_session addOutput:_output];
            }
            _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
            _previewlayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
            _previewlayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
            _previewlayer.frame = self.layer.bounds;
            [self.layer insertSublayer:_previewlayer atIndex:0];
            [_session startRunning];

        }else{//相机不可用
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                NSLog(@"相机不可用");
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您的相机处于不可使用状态，请确认您的相机是否已损坏" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                [alertController addAction:cancelAction];
                [[self getRootViewController] presentViewController:alertController animated:YES completion:nil];
            }
            else if (!isAvailableA)
            {
                NSLog(@"相机权限受限");
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请您设置允许扫描器访问您的相机\n设置>隐私>相机>扫描器" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                    }
                }];
                [alertController addAction:cancelAction];
                [alertController addAction:confirmAction];
                [[self getRootViewController] presentViewController:alertController animated:YES completion:nil];
            }
            !self.backfailure ? : self.backfailure();
        }

    }
    [self addSubview:self.hudView];

    return self;
}
#pragma mark - 开启与关闭闪光灯
-(BOOL)openFlashLamp
{
    BOOL isTurnOn = NO;
    if ([self.input.device hasTorch]) {
        AVCaptureTorchMode torch = self.input.device.torchMode;
        
        switch (_input.device.torchMode) {
            case AVCaptureTorchModeAuto:
                break;
            case AVCaptureTorchModeOff:
                torch = AVCaptureTorchModeOn;
                isTurnOn = YES;
                break;
            case AVCaptureTorchModeOn:
                torch = AVCaptureTorchModeOff;
                isTurnOn = NO;
                break;
            default:
                break;
        }
        
        [_input.device lockForConfiguration:nil];
        _input.device.torchMode = torch;
        [_input.device unlockForConfiguration];
    }
    return isTurnOn;
}

- (CGRect)rectOfInterestByScanViewRect:(CGRect)rect {
    
    CGFloat width = CGRectGetWidth(self.frame);
    CGFloat height = CGRectGetHeight(self.frame);
    
    CGFloat x = rect.origin.y/ height;
    CGFloat y = rect.origin.x/ width;
    
    CGFloat w = CGRectGetHeight(rect) / height;
    CGFloat h = CGRectGetWidth(rect) / width;
    
    return CGRectMake(x, y, w, h);
}


#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects.firstObject;
        !self.backQRCodeURL ? : self.backQRCodeURL(metadataObject.stringValue);
    }
}

-(void)starScaning
{
    if (!_session.isRunning) {
//        NSLog(@"未处于扫描状态，开始扫描");
        [_session startRunning];
    }
//    else
//    {
//        NSLog(@"已处于扫描状态，无需操作");
//    }
}

#pragma mark - lazy
//懵层
- (UIView *)hudView
{
    if (!_hudView) {
        _hudView = [[UIView alloc] initWithFrame:self.bounds];
        CGFloat x = (self.frame.size.width - staticHeight)*0.5;
        CGFloat y = staticTopMargin > 0 ? staticTopMargin : (self.frame.size.height - staticHeight)*0.5;
        CGFloat height = staticHeight;
        //镂空
        CGRect qrRect = CGRectMake(x,y,height, height);
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.frame cornerRadius:0];
        UIBezierPath *circlePath = [UIBezierPath bezierPathWithRect:qrRect];
        [path appendPath:circlePath];
        [path setUsesEvenOddFillRule:YES];
        CAShapeLayer *fillLayer = [CAShapeLayer layer];
        fillLayer.path = path.CGPath;
        fillLayer.fillRule = kCAFillRuleEvenOdd;
        fillLayer.fillColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.4].CGColor;
        fillLayer.opacity = 0.5;
        [_hudView.layer addSublayer:fillLayer];

        //白色矩形
        UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:CGRectMake(x, y, height, height)];
        CAShapeLayer *shapLayer = [CAShapeLayer layer];
        shapLayer.backgroundColor = UIColor.clearColor.CGColor;
        shapLayer.path = bezierPath.CGPath;
        shapLayer.lineWidth = 0.5;
        shapLayer.strokeColor = UIColor.whiteColor.CGColor;
        shapLayer.fillColor = UIColor.clearColor.CGColor;
        [_hudView.layer addSublayer:shapLayer];

        //绿色四个角落
        UIBezierPath *cornerBezierPath = [UIBezierPath bezierPath];

        [cornerBezierPath moveToPoint:CGPointMake(x, y+30)];//左上角
        [cornerBezierPath addLineToPoint:CGPointMake(x, y)];
        [cornerBezierPath addLineToPoint:CGPointMake(x+30, y)];

        [cornerBezierPath moveToPoint:CGPointMake(x+height-30, y)];//右上角
        [cornerBezierPath addLineToPoint:CGPointMake(x+height, y)];
        [cornerBezierPath addLineToPoint:CGPointMake(x+height, y+30)];

        [cornerBezierPath moveToPoint:CGPointMake(x+height, y+height-30)];//左上角
        [cornerBezierPath addLineToPoint:CGPointMake(x+height, y+height)];
        [cornerBezierPath addLineToPoint:CGPointMake(x+height-30, y+height)];

        [cornerBezierPath moveToPoint:CGPointMake(x+30, y+height)];//左上角
        [cornerBezierPath addLineToPoint:CGPointMake(x, y+height)];
        [cornerBezierPath addLineToPoint:CGPointMake(x, y+height-30)];

        CAShapeLayer *cornerShapLayer = [CAShapeLayer layer];
        cornerShapLayer.backgroundColor = UIColor.clearColor.CGColor;
        cornerShapLayer.path = cornerBezierPath.CGPath;
        cornerShapLayer.lineWidth = 3.0;
        cornerShapLayer.strokeColor = STYLECOLOR.CGColor;
        cornerShapLayer.fillColor = UIColor.clearColor.CGColor;
        [_hudView.layer addSublayer:cornerShapLayer];

        //光标
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.frame = CGRectMake(x+3, y+3, height-6, 1.5);
        gradientLayer.colors = [self colorWithBasicColor:STYLECOLOR];
        gradientLayer.startPoint = CGPointMake(0, 0.5);
        gradientLayer.endPoint = CGPointMake(1.0, 0.5);
        [gradientLayer addAnimation:[self positionBasicAnimate] forKey:nil];
        [_hudView.layer addSublayer:gradientLayer];
    }
    return _hudView;
}
//动画
- (CABasicAnimation *)positionBasicAnimate
{
    CGFloat x = (self.frame.size.width - staticHeight)*0.5;
    CGFloat y = staticTopMargin > 0 ? staticTopMargin : (self.frame.size.height - staticHeight)*0.5;
    CGFloat height = staticHeight;
    CABasicAnimation *animate = [CABasicAnimation animationWithKeyPath:@"position"];
    animate.removedOnCompletion = NO;
    animate.duration = 2.0;
    animate.fillMode = kCAFillModeRemoved;
    animate.repeatCount = HUGE_VAL;
    animate.fromValue = [NSValue valueWithCGPoint:CGPointMake(x+height*0.5, y+3)];
    animate.toValue = [NSValue valueWithCGPoint:CGPointMake(x+height*0.5, y+height-3)];
    animate.autoreverses = YES;
    return animate;
}

- (NSArray<UIColor *> *)colorWithBasicColor:(UIColor *)basicCoclor
{
    CGFloat R, G, B, amplitude;
    amplitude = 90/255.0;
    NSInteger numComponents = CGColorGetNumberOfComponents(basicCoclor.CGColor);
    NSArray *colors;
    if (numComponents == 4)
    {
        const CGFloat *components = CGColorGetComponents(basicCoclor.CGColor);
        R = components[0];
        G = components[1];
        B = components[2];
        colors = @[(id)[UIColor colorWithWhite:0.667 alpha:0.2].CGColor,
                   (id)basicCoclor.CGColor,
                   (id)[UIColor colorWithRed:R+amplitude > 1.0 ? 1.0:R+amplitude
                                        green:G+amplitude > 1.0 ? 1.0:G+amplitude
                                        blue:B+amplitude > 1.0 ? 1.0:B+amplitude alpha:1.0].CGColor,
                   (id)[UIColor colorWithRed:R+amplitude > 1.0 ? 1.0:R+amplitude*2
                                        green:G+amplitude > 1.0 ? 1.0:G+amplitude*2
                                        blue:B+amplitude > 1.0 ? 1.0:B+amplitude*2 alpha:1.0].CGColor,
                   (id)[UIColor colorWithRed:R+amplitude > 1.0 ? 1.0:R+amplitude
                                        green:G+amplitude > 1.0 ? 1.0:G+amplitude
                                        blue:B+amplitude > 1.0 ? 1.0:B+amplitude alpha:1.0].CGColor,
                   (id)basicCoclor.CGColor,
                   (id)[UIColor colorWithWhite:0.667 alpha:0.2].CGColor,];
    }else{
        colors = @[(id)basicCoclor.CGColor,
                   (id)basicCoclor.CGColor,];
    }
    return colors;
}



- (UIViewController *)getRootViewController{

    UIWindow* window = [self getWindow];
//    NSAssert(window, @"The window is empty");
    return window.rootViewController;
}

- (UIWindow *)getWindow
{
    UIWindow* window = nil;

    if (@available(iOS 13.0, *))
    {
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes)
        {
            if (windowScene.activationState == UISceneActivationStateForegroundActive)
            {
                window = windowScene.windows.firstObject;
                break;
            }
        }
    }else{
        window = [UIApplication sharedApplication].keyWindow;
    }
    return window;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end



/**
 
 
 
 
 AVCaptureMetadataOutput 中的属性rectOfInterest 看起来是CGRect类型, 结果让你填写一个比例, 当你填写比例是你会发现还是有各种问题,  最后总结一下, 加入你的屏幕的frame 为  x , y,  w, h,  你要设置的矩形快的frame  为  x1, y1, w1, h1.   那么你的 rectOfInterest 应该设置为   CGRectMake(y1/y, x1/x, h1/h, w1/w),
  

 [output setRectOfInterest:[self rectOfInterestByScanViewRect:你的扫描框的rect];

 - (CGRect)rectOfInterestByScanViewRect:(CGRect)rect {
     
     CGFloat width = CGRectGetWidth(self.view.frame);
     CGFloat height = CGRectGetHeight(self.view.frame);
     
     CGFloat x = rect.origin.y/ height;
     CGFloat y = rect.origin.x/ width;
     
     CGFloat w = CGRectGetHeight(rect) / height;
     CGFloat h = CGRectGetWidth(rect) / width;
     
     return CGRectMake(x, y, w, h);
 }

 
 
 
 
 
 */




